import * as zlib from 'zlib'
import { F2EConfig } from 'f2e-server'
import { IncomingMessage, ServerResponse } from "http";
import { Config } from "../interface";
import { PLACE_HOLDER } from "../utils";

export const admin_index = ({
    get_admin_page, dev, admin_page, admin_url
}: Config, getLayoutPage: () => string, renderHeaders: F2EConfig['renderHeaders'] = (h => h)) => (req: IncomingMessage, resp: ServerResponse) => {
    let output = getLayoutPage().replace(PLACE_HOLDER, get_admin_page
        ? get_admin_page()
        : admin_page ? admin_page.replace('{{admin_url}}', admin_url || '') : ''
    );
    if (dev) {
        output = (getLayoutPage().replace(PLACE_HOLDER, (admin_page || '').replace('{{admin_url}}/bundle.js', 'lib/bundle.js') + `
            <script> if(window.EventSource) { new EventSource('/server-sent-bit').onmessage = function (e) { e.data === 'true' && location.reload() } } </script>
            `))
    }
    resp.writeHead(200, renderHeaders({
        'Content-Encoding': 'gzip',
        'Content-Type': 'text/html; charset=utf-8'
    }, req))
    resp.end(zlib.gzipSync(output))
}